#include "demo.h"
#include "tim.h"

//const uint8_t Days[12] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31};
const uint16_t AddMonDays[12] = {0,31, 59, 90, 120, 151, 181, 212, 243, 273, 304, 334};
uint8_t edge_Event_flag = 0;

uint32_t ConvertStamp(RTC_DateTypeDef sDate, RTC_TimeTypeDef sTime)    //
{
	uint32_t result;
	uint16_t Year=sDate.Year+2000;
	result = (Year - 1970) * 365 + AddMonDays[sDate.Month-1] + sDate.Date - 1;
	result += (sDate.Month>2 && (Year % 4 == 0) && (Year % 100 != 0 || Year % 400 == 0));
	Year -= 1970;
	result += (Year/4 - Year/100 + Year/400);
//	result = result * 24 * 3600 + (sTime.Hours-8) * 3600 + sTime.Minutes * 60 + sTime.Seconds;
	result = result * (675<<7) + (sTime.Hours-8) * (225<<4) + sTime.Minutes * 60 + sTime.Seconds;
	return result;
}

HAL_StatusTypeDef Get_TimeStamp(uint32_t* timestamp)
{
	RTC_TimeTypeDef sTime = {0};
	RTC_DateTypeDef sDate = {0};
	if(HAL_OK == HAL_RTC_GetTime(&hrtc, &sTime, RTC_FORMAT_BIN)
			&& HAL_OK == HAL_RTC_GetDate(&hrtc, &sDate, RTC_FORMAT_BIN))
	{
			*timestamp = ConvertStamp(sDate,sTime);  
			BB_MSG(BB_MSG_LEVEL_DEBUG,"20%d--%d--%d  %d:%d:%d",sDate.Year,sDate.Month,sDate.Date,sTime.Hours,sTime.Minutes,sTime.Seconds);
//			BB_MSG(BB_MSG_LEVEL_INFO,"Time Stamp:%u",*timestamp);	
			return HAL_OK ;
	}
	return HAL_ERROR ;
}

void Get_EdgeTime(void)
{
	int32_t cultime = 0;
	if(edge_Event_flag)
	{
		cultime = __HAL_TIM_GET_COUNTER(&htim3);
		HAL_GPIO_TogglePin(GPIOA,GPIO_PIN_4);
		while(HAL_GPIO_ReadPin(GPIOA,GPIO_PIN_0) == GPIO_PIN_SET);
		cultime = __HAL_TIM_GET_COUNTER(&htim3) - cultime;
		HAL_GPIO_TogglePin(GPIOA,GPIO_PIN_4);
		HAL_TIM_Base_Stop_IT(&htim3);
		if(cultime < 0)	//Test time run out
			BB_MSG(BB_MSG_LEVEL_INFO,"Test time run out");
		else
		{
			BB_MSG(BB_MSG_LEVEL_INFO,"%dus",cultime);
			if((cultime>90)&&(cultime<120))
				BB_MSG(BB_MSG_LEVEL_INFO,"Interrupt INT1");
			if((cultime>900)&&(cultime<1200))
				BB_MSG(BB_MSG_LEVEL_INFO,"Interrupt DRDY");
		}
		edge_Event_flag = 0;
	}
}

void HAL_GPIO_EXTI_Callback(uint16_t GPIO_Pin)
{	
	//External interrupt PIN_A0 service function
	if(GPIO_Pin == GPIO_PIN_0)	
	{
		__HAL_TIM_SET_COUNTER(&htim3,0);
		HAL_TIM_Base_Start_IT(&htim3);
		edge_Event_flag = 1;
	}
}



